package com.imooc;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * 存放备选课程的List
 * @author admin
 *
 */
public class ListTest {

	public List coursesToSelect;
	
	public ListTest() {
		this.coursesToSelect =  new ArrayList();
	}
	
	public void testAdd() {
		//创建一个课程对象
		Course cr1 = new Course("1", "数据结构");
		coursesToSelect.add(cr1);
		Course temp = (Course) coursesToSelect.get(0);
		System.out.println("添加了课程->" + temp.id + "-" + temp.name);
		
		Course cr2 = new Course("2", "Java程序设计");
		coursesToSelect.add(0, cr2);
		Course temp2 = (Course)coursesToSelect.get(0);
		System.out.println("添加了课程->" + temp2.id + "-" + temp2.name);
		
		
		//
		Course[] crs = {new Course("3", "算法精通"), new Course("4", "python从入门到放弃")};
		coursesToSelect.addAll(Arrays.asList(crs));
		Course temp3 = (Course)coursesToSelect.get(2);
		Course temp4 = (Course)coursesToSelect.get(3);
		
		System.out.println("添加了两门课程：" + temp3.id + "-" + temp3.name + "和" + 
				temp4.id + "-" + temp4.name);
		
		Course[] crs2 = {new Course("5", "高等数学"), new Course("6", "计算机英语")};
		coursesToSelect.addAll(2, Arrays.asList(crs2));		//插入2位置
		Course temp5 = (Course)coursesToSelect.get(2);
		Course temp6 = (Course)coursesToSelect.get(3);
		System.out.println("添加了两门课程：" + temp5.id + "-" + temp5.name + "和" + 
				temp6.id + "-" + temp6.name);
	}
	
	/**
	 * 课表查询，获取元素
	 */
	public void testGet() {
		System.out.println("有以下课程可选（数组遍历）：");
		for(int i=0; i < this.coursesToSelect.size(); i++) {
			Course cr = (Course)coursesToSelect.get(i);
			System.out.println("课程：" + cr.id + "->"  + cr.name);
		}
	}
	/**
	 * 通过迭代器遍历List
	 * Iterator是一个接口，依赖于集合存在
	 */
	public void testIterator() {
		System.out.println("有以下课程可选（迭代器遍历）：");
		//通过iterator方法获得一个实例
		Iterator it = coursesToSelect.iterator();
		while(it.hasNext()) {
			Course cr = (Course)it.next();
			System.out.println("课程：" + cr.id + "->"  + cr.name);
		}
	}
	
	/**
	 * 通过for each 方法遍历
	 */
	public void testForEach() {
		System.out.println("有以下课程可选（for each遍历）：");
		for(Object obj : coursesToSelect) {
			Course cr = (Course)obj;
			System.out.println("课程：" + cr.id + "->"  + cr.name);
		}
	}
	
	/**
	 * set()方法修改List元素
	 */
	public void testModify() {
		coursesToSelect.set(5, new Course("4", "Python从入门到大神"));
	}
	/**
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		ListTest lt = new ListTest();
		lt.testAdd();
		lt.testGet();
		lt.testIterator();
		lt.testModify();
		lt.testForEach();
	}
}
